package com.zhiyin.seal.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.mysql.cj.util.StringUtils;
import com.zhiyin.seal.constant.SystemConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        // 设置请求运行跨域
        this.crossDomainConfig(response);
        String requestURL = request.getServletPath();
        // 拦截admin-web接口
        if(requestURL.startsWith("/admin-web")){
            // 不拦截登录接口
            if(requestURL.endsWith("login")){
                return true;
            } else {
                // 获取token
                String accessToken = request.getHeader("x-access-token");
                if(StringUtils.isNullOrEmpty(accessToken)){
                    writeResponse(response);

                    return false;
                }
                //调用解密方法
                Claims claims= Jwts.parser()
                        .setSigningKey(SystemConstants.WEB_TOKEN_SALT_FIGURE)
                        .parseClaimsJws(accessToken)
                        .getBody();
                //解密ID
                Integer id=Integer.valueOf(claims.getId());
                //解密用户名
                String username=claims.getSubject();
                if(username == null || id == null){
                    writeResponse(response);

                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 配置跨域
     *
     * @param response
     */
    private void crossDomainConfig(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers", "x-access-token");
        response.setHeader("Access-Control-Max-Age", "3628800");
    }

    /**
     * 写入响应流
     * @param response
     */
    private void writeResponse(HttpServletResponse response){
        //设置response，手动返回response响应;
        response.setContentType("application/json;charset=utf-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",-1);
        jsonObject.put("msg","禁止访问");
        try {
            response.getWriter().write(JSONObject.toJSONString(jsonObject));
            response.getOutputStream().close();
        } catch (Exception ex){

        }
    }
}
